package com.yxd.demo.rule;

import com.yxd.demo.domain.Coupon;
import com.yxd.demo.domain.Product;
import com.yxd.demo.service.MarketingWayService;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;
import org.jeasy.rules.api.Facts;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: yxd
 * @date: 2022/8/8 10:11
 */
@Component(value = "priceRule")
@Rule(name = "金额规则", description = "判断商品金额是否超过金额阈值", priority = 10)
public class PriceRule {

    @Condition
    public boolean condition(Facts facts) {
        List<Coupon> couponList = facts.get("couponList");
        return !CollectionUtils.isEmpty(couponList);
    }

    @Action
    public void action(Facts facts) {
        List<Coupon> usableCouponList = new ArrayList<>();
        Product product = facts.get("product");
        List<Coupon> couponList = facts.get("couponList");
        for (Coupon coupon : couponList) {
            //立减券直接使用
            if (Objects.equals(coupon.getType(), 1)) {
                usableCouponList.add(coupon);
                continue;
            }
            //满减券判断商品价格是否超过阈值
            BigDecimal threshold = coupon.getThreshold();
            Integer productNum = product.getProductNum();
            BigDecimal productPrice = product.getProductPrice();
            BigDecimal currPrice = MarketingWayService.multiply(BigDecimal.valueOf(productNum), productPrice);
            if (!MarketingWayService.compareTo(currPrice, threshold)) {
                continue;
            }
            usableCouponList.add(coupon);
        }
        facts.put("couponList", usableCouponList);
    }
}
